<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户" prop="userId" class="selectUser">
        <el-select v-model="queryParams.userId" placeholder="请选择用户" clearable>
          <el-option v-for="user in UserList" :key="user.id" :label="user.nickName" :value="user.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="救援类型" prop="rescueTypeId" class="rescueType">
        <el-select v-model="queryParams.rescueTypeId" placeholder="请选择救援类型" clearable>
          <el-option v-for="dict in rescue" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="商家" prop="merchantId" class="merchant">
        <el-input v-model="merchantName" placeholder="请输入商家名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['mp:rescue:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['mp:rescue:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['mp:rescue:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['mp:rescue:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="rescueList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" width="55" align="center" prop="id" />
      <el-table-column label="用户" align="center" prop="userId">
        <template #default="scope">
          {{UserList.find(user => user.id === scope.row.userId)?.nickName || '-'}}
        </template>
      </el-table-column>
      <el-table-column label="救援类型" align="center" prop="rescueTypeId">
        <template #default="scope">
          <dict-tag :options="rescue" :value="scope.row.rescueTypeId" />
        </template>
      </el-table-column>
      <el-table-column label="车牌号" align="center" prop="carId">
        <template #default="scope">
          {{carList.find(car => car.uid === scope.row.userId && car.id === scope.row.carId)?.carNum || '-'}}
        </template>
      </el-table-column>
      <el-table-column label="商家" align="center" prop="merchantId">
        <template #default="scope">
          {{merchantList.find(merchant => merchant.id === scope.row.merchantId)?.name || '-'}}
        </template>
      </el-table-column>
      <el-table-column label="救援位置" align="center" prop="rescuePosition" />
      <el-table-column label="结束位置" align="center" prop="endPosition" />
      <el-table-column label="救援时间" align="center" prop="rescueTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.rescueTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户评分" align="center" prop="score">
        <template #default="scope">
          <el-rate v-model="scope.row.score" disabled />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['mp:rescue:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['mp:rescue:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改救援任务对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="rescueRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户" prop="userId">
          <el-select v-model="form.userId" placeholder="请选择用户id" @change="handleUserChange" clearable>
            <el-option v-for="user in UserList" :key="user.id" :label="user.nickName" :value="user.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="救援类型" prop="rescueTypeId">
          <el-select v-model="form.rescueTypeId" placeholder="请选择救援类型id">
            <el-option v-for="dict in rescue" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="车辆号" prop="carId">
          <el-select v-model="form.carId" placeholder="请选择车辆id" :disabled="!form.userId" clearable>
            <el-option v-for="car in carList" :key="car.id" :label="car.carNum" :value="car.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="商家" prop="merchantId">
          <el-select v-model="form.merchantId" placeholder="请选择商家id" clearable>
            <el-option v-for="merchant in merchantList" :key="merchant.id" :label="merchant.name"
              :value="merchant.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="救援位置" prop="rescuePosition">
          <el-input v-model="form.rescuePosition" placeholder="请输入救援位置" />
        </el-form-item>
        <el-form-item label="结束位置" prop="endPosition">
          <el-input v-model="form.endPosition" placeholder="请输入结束位置" />
        </el-form-item>
        <el-form-item label="救援时间" prop="rescueTime">
          <el-date-picker clearable v-model="form.rescueTime" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择救援时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="用户评分" prop="score">
          <el-rate v-model="form.score" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Rescue">
import { listRescue, getRescue, delRescue, addRescue, updateRescue } from "@/api/mp/rescue"
import { listInfo } from "@/api/bigbase/info"
import { listCarInfo } from "@/api/bigbase/carInfo"
import { listMerchant } from "@/api/merchant/merchant"

const { proxy } = getCurrentInstance()
const { rescue } = proxy.useDict('rescue')

const rescueList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const merchantName = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: null,
    rescueTypeId: null,
    carId: null,
    merchantId: null,
  },
  rules: {
    userId: [
      { required: true, message: "用户id不能为空", trigger: "blur" }
    ],
    rescueTypeId: [
      { required: true, message: "救援类型id不能为空", trigger: "change" }
    ],
    carId: [
      { required: true, message: "车辆id不能为空", trigger: "blur" }
    ],
    merchantId: [
      { required: true, message: "商家id不能为空", trigger: "blur" }
    ],
    rescuePosition: [
      { required: true, message: "救援位置不能为空", trigger: "blur" }
    ],
    rescueTime: [
      { required: true, message: "救援时间不能为空", trigger: "blur" }
    ],
    score: [
      { required: true, message: "用户评分不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询救援任务列表 */
function getList() {
  loading.value = true
  listRescue(queryParams.value).then(response => {
    rescueList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  queryCarParams.value = {
    pageNum: 1,
    pageSize: 10,
    uid: null,
    brand: null,
    type: null,
    carNum: null,
    default: null
  }
  getCarList()
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    userId: null,
    rescueTypeId: null,
    carId: null,
    merchantId: null,
    rescuePosition: null,
    endPosition: null,
    rescueTime: null,
    score: null,
    del: null
  }
  proxy.resetForm("rescueRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  if (merchantName.value != null) {
    queryParams.value.merchantId = merchantList.value.find(merchant => merchant.name === merchantName.value)?.id || -1
  }
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  merchantName.value = null
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加救援任务"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getRescue(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改救援任务"
  })
}

/** 提交按钮 */
function submitForm() {
  queryCarParams.value = {
    pageNum: 1,
    pageSize: 10,
    uid: null,
    brand: null,
    type: null,
    carNum: null,
    default: null
  }
  getCarList()
  proxy.$refs["rescueRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateRescue(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addRescue(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除救援任务编号为"' + _ids + '"的数据项？').then(function () {
    return delRescue(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('mp/rescue/export', {
    ...queryParams.value
  }, `rescue_${new Date().getTime()}.xlsx`)
}

// 查询用户列表
const queryUserParams = reactive({
  pageNum: 1,
  pageSize: 10,
  userName: null,
  nickName: null,
  phone: null,
  email: null,
  regTime: null,
  status: null,
})
const UserList = ref([])
function getUserList() {
  listInfo(queryUserParams.value).then(response => {
    UserList.value = response.rows
  })
}

// 查询用户车辆列表
const queryCarParams = reactive({
  pageNum: 1,
  pageSize: 10,
  uid: null,
  brand: null,
  type: null,
  carNum: null,
  default: null
})
const carList = ref([])
function getCarList() {
  listCarInfo(queryCarParams.value).then(response => {
    carList.value = response.rows
    console.log(carList.value)
  })
}

// 查询商家列表
const queryMerchantParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: null,
  operatingArea: null,
  regTime: null,
  startTime: null,
  endTime: null,
  address: null,
  longitude: null,
  latitude: null,
  description: null,
  rate: null,
  status: null,
  del: null,
  auditStatusId: null
})
const merchantList = ref([])
function getMerchantList() {
  listMerchant(queryMerchantParams.value).then(response => {
    merchantList.value = response.rows
  })
}

// 选择用户后触发，动态加载车辆
const handleUserChange = async (userId) => {
  form.value.carId = '' // 重置车辆选择
  if (userId) {
    queryCarParams.value = {
      pageNum: 1,
      pageSize: 10,
      uid: userId,
      brand: null,
      type: null,
      carNum: null,
      default: null
    }
    const res = await listCarInfo(queryCarParams.value)
    carList.value = res.rows || []
  } else {
    carList.value = []
  }
}

getList()
getUserList()
getCarList()
getMerchantList()
</script>
<style scoped>
.selectUser {
  width: 200px;
}

.rescueType {
  width: 220px;
}

.merchant {
  width: 210px;
}
</style>
